<script>
import { post } from './utils/request'
export default {
  onLaunch: function () {
    // 检查登录状态
    const token = uni.getStorageSync('token')
    if (!token) {
      uni.reLaunch({
        url: '/pages/login/index'
      })
    }
  },
  onShow: function () {},
  onHide: function () {},

  // 供其他页面调用的登录方法
  methods: {
    login() {
      return new Promise(function (resolve, reject) {
        uni.login({
          success: function (res) {
            if (res.code) {
              resolve(res)
            } else {
              reject(res)
            }
          },
          fail: function (err) {
            reject(err)
          }
        })
      })
    },

    // 获取用户信息并登录
    getUserProfile() {
      return new Promise((resolve, reject) => {
        uni.getUserProfile({
          desc: '用于完善会员资料',
          success: res => {
            let userInfo = res.userInfo
            this.login()
              .then(loginRes => {
                post('auth/login_by_weixin', {
                  code: loginRes.code,
                  userInfo: userInfo
                })
                  .then(res => {
                    uni.setStorageSync('userInfo', res.data.userInfo)
                    uni.setStorageSync('token', res.data.token)
                    resolve(res)
                  })
                  .catch(err => {
                    reject(err)
                  })
              })
              .catch(err => {
                reject(err)
              })
          },
          fail: error => {
            console.log('获取用户信息失败', error)
            reject(error)
          }
        })
      })
    }
  }
}
</script>

<style lang="scss">
@import 'uview-ui/index.scss';
@import '~@/static/styles/app.scss';
@import './static/styles/iconfont.css';
</style>
